﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>入库订单管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            background-color: #f0f2f5;
            margin: 0;
            padding: 0;
            font-family: "PingFang SC", "Microsoft Yahei", sans-serif;
        }

        .container {
            width: 1200px;
            margin-left: 20px;
            margin-top: 20px;
            background-color: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            padding: 24px;
        }

        .search-area {
            margin-bottom: 16px;
            padding: 16px;
            background-color: #f5f7fa;
            border-radius: 4px;
        }

        .btn-group {
            margin-bottom: 16px;
            display: flex;
            gap: 8px;
        }

        .table-container {
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            overflow: hidden;
        }

        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        @@keyframes fadeIn {
            from

        {
            opacity: 0;
        }

        to {
            opacity: 1;
        }

        }

        .el-table__header th {
            background-color: #f0f2f5 !important;
        }

        .el-table__header .el-table__header-cell .cell {
            font-weight: bold !important;
        }
    </style>
</head>
<body>
    <div id="inbound-order-app" class="container fade-in">
        <!-- 搜索区域：入库订单筛选条件 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="入库单号">
                    <el-input v-model="searchForm.WarehouseReceiptNo" placeholder="请输入入库单号"></el-input>
                </el-form-item>
                <el-form-item label="入库类型">
                    <el-select v-model="searchForm.DocumentStatu" placeholder="请选择">
                        <el-option v-for="item in warehousingTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单据状态">
                    <el-select v-model="searchForm.Status" placeholder="请选择">
                        <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="searchForm.dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    clearable></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="handleSearch">查询</el-button>
                    <el-button v-on:click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 功能按钮区域 -->
        <div class="btn-group">
            <el-button type="primary" v-on:click="handleAdd">新增</el-button>
            <el-button v-on:click="handleDelete">删除</el-button>
            <el-button v-on:click="openAuditDialog">审核</el-button>
            <el-button v-on:click="handleExport">导出</el-button>
            <el-button v-on:click="handleImport">导入</el-button>
            <el-button v-on:click="handleRefresh">刷新</el-button>
        </div>

        <!-- 数据表格区域：入库订单字段 -->
        <div class="table-container">
            <el-table :data="tableData" ref="multipleTableRef" @@selection-change ="handleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="purchase_order_no" label="入库单号" width="170" fixed="left">
                    <template #default="scope">
                        <span v-on:click="handleDetail(scope.row)" style="cursor: pointer; color: #409EFF;">
                            {{ scope.row.purchase_order_no }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="入库类型" fixed="left" width="120">
                    <template #default="scope">
                        {{ warehousingTypeOptions.find(item => item.dictValue === scope.row.document_statu)?.dictLabel || '未知' }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" width="120">
                    <template #default="scope">
                        {{ statusOptions.find(item => item.dictValue === scope.row.status)?.dictLabel || '未知' }}
                    </template>
                </el-table-column>
                <el-table-column prop="purchase_date" label="入库日期" width="120">
                    <template #default="scope">
                        {{ new Date(scope.row.purchase_date).toLocaleDateString() }}
                    </template>
                </el-table-column>
                <el-table-column prop="contact_person" label="仓库名称" width="120"></el-table-column>
                <el-table-column prop="contact_information" label="关联单号" width="180"></el-table-column>
                <el-table-column prop="organizations_id" label="入库货品" width="120"></el-table-column>
                <el-table-column prop="purchaser" label="经办人" width="120"></el-table-column>
                <el-table-column prop="warehouse_receipt_id" label="入库单ID" width="0" visible="false"></el-table-column>
                <el-table-column prop="totalQuantity" label="入库数量" width="120"></el-table-column>
                <el-table-column label="入库金额" width="120">
                    <template #default="scope">
                        {{ scope.row.totalAmount !== undefined ? scope.row.totalAmount.toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
                <el-table-column prop="productNames" label="制单人" width="180"></el-table-column>
                <el-table-column prop="create_by" label="所在部门" width="160"></el-table-column>
                <el-table-column prop="create_time" label="制单时间" width="300">
                    <template #default="scope">
                        {{ new Date(scope.row.create_time).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column prop="reviewer" label="审核人" width="120"></el-table-column>
                <el-table-column prop="review_time" label="审核时间" width="180">
                    <template #default="scope">
                        {{ scope.row.review_time ? new Date(scope.row.review_time).toLocaleString() : '未审核' }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <!-- 未审核状态：显示编辑和删除按钮 -->
                        <template v-if="scope.row.status === '未审核'">
                            <el-button link type="primary" size="small" v-on:click="handleEdit(scope.row)">编辑</el-button>
                            <el-button link type="danger" size="small" v-on:click="handleDeleteRow(scope.row)">删除</el-button>
                        </template>

                        <!-- 未入库状态：显示撤回按钮 -->
                        <template v-else-if="scope.row.status === '未入库'">
                            <el-button link type="warning" size="small" v-on:click="handleWithdraw(scope.row)">撤回</el-button>
                        </template>

                        <!-- 其他状态：可根据需求隐藏或显示其他按钮 -->
                        <template v-else>
                            <!-- 例如：已审核状态不显示操作按钮 -->
                        </template>
                    </template>
                </el-table-column>
            </el-table>

            <div style="margin-top: 16px; text-align: right;">
                <el-pagination v-model:current-page="currentPage"
                               v-model:page-size="pageSize"
                               :page-sizes="[5, 10, 20, 50]"
                               :total="total"
                               layout="total, sizes, prev, pager, next, jumper"
                               v-on:size-change="handlePageSizeChange"
                               v-on:current-change="handleCurrentPageChange"></el-pagination>
            </div>
        </div>

        <el-dialog v-model="auditDialogVisible" title="入库单审核" width="50%" :close-on-click-modal="false">
            <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="120px">
                <el-form-item label="审核结果" prop="isApproved">
                    <el-radio-group v-model="auditForm.isApproved">
                        <el-radio label="true">通过</el-radio>
                        <el-radio label="false">驳回</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="审核意见" prop="opinion">
                    <el-input v-model="auditForm.opinion"
                              type="textarea"
                              rows="4"
                              placeholder="请输入审核意见（驳回时必填）"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button v-on:click ="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="handleAuditSubmit">确认审核</el-button>
            </template>
        </el-dialog>
    </div>

    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <script>
        const { createApp, ref, reactive, onMounted } = Vue;
        createApp({
            setup() {
                // 分页相关
                const currentPage = ref(1);
                const pageSize = ref(10);
                const total = ref(0);

                // 搜索表单（与实体类InboundQueryParam字段对应）
                const searchForm = reactive({
                    WarehouseReceiptNo: '',   // 入库单号（模糊查询）
                    DocumentStatu: null,     // 入库类型ID
                    Status: '',              // 单据状态
                    dateRange: []            // 时间范围
                });

                // 表格数据（与实体类InboundQueryResult字段对应）
                const tableData = ref([]);

                // 字典数据（用于类型/状态的文本映射）
                const warehousingTypeOptions = ref([]); // 入库类型字典
                const statusOptions = ref([]);         // 单据状态字典

                const loadDictData = async () => {
                    // 加载入库类型字典（转换dictValue为数字）
                    const typeRes = await axios.get('/api/Dict/datas/WarehousingType');
                    warehousingTypeOptions.value = typeRes.data.map(item => ({
                        dictValue: parseInt(item.dictValue), // 字符串转数字
                        dictLabel: item.dictLabel
                    }));

                    // 加载单据状态字典（转换dictValue为数字）
                    const statusRes = await axios.get('/api/Dict/datas/StockOrderStatus');
                    statusOptions.value = statusRes.data.map(item => ({
                        dictValue: parseInt(item.dictValue), // 字符串转数字
                        dictLabel: item.dictLabel
                    }));
                };

                // 加载入库订单数据（接口：/api/InboundOrder/QueryPaged）
                const loadOrderData = async () => {
                    try {
                        const params = {
                            currentPage: currentPage.value,
                            pageSize: pageSize.value,
                            WarehouseReceiptNo: searchForm.WarehouseReceiptNo,
                            DocumentStatu: searchForm.DocumentStatu,
                            Status: searchForm.Status,
                            StartDate: searchForm.dateRange[0]?.toISOString().split('T')[0],
                            EndDate: searchForm.dateRange[1]?.toISOString().split('T')[0]
                        };
                        const response = await axios.get('/api/InboundOrder/QueryPaged', { params });
                        if (response.data.code === 200) {
                            console.log(response.data.data);
                            tableData.value = response.data.data;
                            total.value = response.data.total;
                        } else {
                            ElementPlus.ElMessage.error(response.data.message || '查询失败');
                        }
                    } catch (error) {
                        console.error('加载数据失败', error);
                        ElementPlus.ElMessage.error('网络异常，请重试');
                    }
                };

                // 搜索
                const handleSearch = () => {
                    currentPage.value = 1;
                    loadOrderData();
                };

                // 重置
                const handleReset = () => {
                    searchForm.WarehouseReceiptNo = '';
                    searchForm.DocumentStatu = null;
                    searchForm.Status = '';
                    searchForm.dateRange = [];
                    currentPage.value = 1;
                    loadOrderData();
                };

                // 分页-每页条数变化
                const handlePageSizeChange = (newSize) => {
                    pageSize.value = newSize;
                    loadOrderData();
                };

                // 分页-页码变化
                const handleCurrentPageChange = (newPage) => {
                    currentPage.value = newPage;
                    loadOrderData();
                };

                // 新增
                const handleAdd = () => {
                    window.location.href = '/StockIn/AddPage';
                };

                // 删除（批量）
                const handleDelete = () => {
                    console.log('批量删除入库订单');
                };

                // 导出
                const handleExport = () => {
                    console.log('导出入库订单数据');
                };

                // 导入
                const handleImport = () => {
                    console.log('导入入库订单数据');
                };

                // 刷新
                const handleRefresh = () => {
                    loadOrderData();
                };

                // 编辑
                const handleEdit = (row) => {
                    console.log('编辑入库订单：', row);
                    // 实际路由示例：window.location.href = `/InboundOrder/Edit?id=${row.warehouse_receipt_id}`;
                };

                // 单条删除
                const handleDeleteRow = async (row) => {
                    try {
                        const confirmResult = await ElementPlus.ElMessageBox.confirm(
                            `确定要删除入库订单【${row.purchase_order_no}】吗？`,
                            "删除确认",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }
                        );

                        if (confirmResult === "confirm") {
                            // 调用删除接口示例（需后端配合）
                            // const response = await axios.post("/api/InboundOrder/Delete", null, {
                            //     params: { warehouse_receipt_id: row.warehouse_receipt_id }
                            // });
                            // if (response.data.success) {
                            //     ElementPlus.ElMessage.success("删除成功");
                            //     loadOrderData();
                            // } else {
                            //     ElementPlus.ElMessage.error(response.data.message);
                            // }
                            ElementPlus.ElMessage.success("删除逻辑待实现");
                        }
                    } catch (error) {
                        if (error !== "cancel") {
                            console.error("删除失败：", error);
                            ElementPlus.ElMessage.error("删除失败，请重试");
                        }
                    }
                };

                // 查看详情
                const handleDetail = (row) => {
                    window.location.href = `/InboundOrder/DetailsPage?orderNo=${row.purchase_order_no}`;
                };

                // 审核模态框相关
                const auditDialogVisible = ref(false);
                const auditForm = reactive({
                    result: '通过', // 初始化审核结果为“通过”
                    opinion: '',     // 初始化审核意见为空
                    isApproved:true,
                });
                const selectedOrders = ref([]);
                const multipleTableRef = ref(null);

                const handleSelectionChange = (val) => {
                    selectedOrders.value = val;
                };

                const openAuditDialog = () => {
                    if (selectedOrders.value.length === 0) {
                        ElementPlus.ElMessage.warning('请选择要审核的订单');
                        return;
                    }
                    auditDialogVisible.value = true;
                };

            const handleAuditSubmit = async () => {
          if (selectedOrders.value.length === 0) {
            ElementPlus.ElMessage.warning('请选择要审核的订单');
            return;
          }
          // 仅支持单条审核（入库单审核为单实体操作）
          const selectedOrder = selectedOrders.value[0];
          if(auditForm.isApproved == 'true'){
              auditForm.isApproved = true
          }else{
              auditForm.isApproved = false
          }
          const auditRequest = {
            WarehouseReceiptId: selectedOrder.warehouse_receipt_id, // 传递入库单ID（后端主键）
            IsApproved: auditForm.isApproved, // 布尔值：true=通过，false=驳回
            Reviewer: '当前登录用户名', // 从登录态获取，示例用admin
            Opinion: auditForm.opinion
          };
          console.log(auditRequest)
          try {
            const response = await axios.post('/api/StockIn/Audit', auditRequest);
            if (response.data.success) {
              ElementPlus.ElMessage.success('审核成功');
              auditDialogVisible.value = false;
              loadOrderData(); // 刷新列表
            } else {
              ElementPlus.ElMessage.error(response.data.message || '审核失败');
            }
          } catch (error) {
            console.error('审核接口调用失败：', error);
            ElementPlus.ElMessage.error('网络异常，请重试');
          }
        };

                // 撤回操作
                const handleWithdraw = async (row) => {
                    try {
                        const confirmResult = await ElementPlus.ElMessageBox.confirm(
                            `确定要撤回订单【${row.purchase_order_no}】吗？`,
                            "撤回确认",
                            {
                                confirmButtonText: "确定",
                                cancelButtonText: "取消",
                                type: "warning"
                            }
                        );

                        if (confirmResult === "confirm") {
                            // 调用撤回接口示例（需后端配合）
                            const response = await axios.post('/api/InboundOrder/Withdraw', {
                                orderNo: row.purchase_order_no
                            });
                            if (response.data.success) {
                                ElementPlus.ElMessage.success('撤回成功');
                                loadOrderData(); // 刷新表格
                            } else {
                                ElementPlus.ElMessage.error(response.data.message);
                            }
                        }
                    } catch (error) {
                        if (error !== "cancel") {
                            console.error("撤回失败：", error);
                            ElementPlus.ElMessage.error("撤回失败，请重试");
                        }
                    }
                };
                
                // 页面初始化
                onMounted(async () => {
                    await loadDictData();
                    await loadOrderData();
                });

                return {
                    searchForm,
                    tableData,
                    handleSearch,
                    handleReset,
                    handleAdd,
                    handleDelete,
                    handleExport,
                    handleImport,
                    handleRefresh,
                    handleDetail,
                    handleEdit,
                    handleDeleteRow,
                    currentPage,
                    pageSize,
                    total,
                    handlePageSizeChange,
                    handleCurrentPageChange,
                    auditDialogVisible,
                    openAuditDialog,
                    auditForm,
                    selectedOrders,
                    multipleTableRef,
                    handleSelectionChange,
                    handleAuditSubmit,
                    handleWithdraw,
                    warehousingTypeOptions,
                    statusOptions
                };
            }
        }).use(ElementPlus).mount('#inbound-order-app');
    </script>
</body>
</html>